package com.oneday.nuo.base.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oneday.nuo.base.common.NuoUtil;
import com.oneday.nuo.base.config.BaseService;

import com.oneday.nuo.base.dao.NuoUserDAO;
import com.oneday.nuo.base.dto.NuoUserDTO;
import com.oneday.nuo.base.entity.NuoAuthEntity;
import com.oneday.nuo.base.entity.NuoDeptEntity;
import com.oneday.nuo.base.entity.NuoUserEntity;
import com.oneday.nuo.base.exception.NuoException;
import com.oneday.nuo.base.response.NuoErrorStatus;
import com.oneday.nuo.base.security.password.NuoPasswordEncoder;
import com.oneday.nuo.base.service.NuoDeptService;
import com.oneday.nuo.base.service.NuoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * 用户表(NuoUser)表服务实现类
 *
 * @author liushuai
 * @since 2021-03-13 23:37:51
 */
@Service("nuoUserService")
@Slf4j
public class NuoUserServiceImpl extends BaseService<NuoUserDAO, NuoUserEntity> implements NuoUserService {

    @Autowired
    private NuoUserDAO nuoUserDao;
    @Autowired
    private NuoPasswordEncoder nuoPasswordEncoder;
    @Autowired
    private NuoDeptService nuoDeptService;


    @Override
    public void saveUser(NuoUserDTO nuoUserDTO) {
        //用户登录名
        if(queryUserFieldIsExist(NuoUserEntity::getUserName,nuoUserDTO.getUserName(),nuoUserDTO.getId())){
            log.error("用户名已存在->{}",nuoUserDTO.getUserName());
            throw new NuoException("用户名已存在");
        }
        //用户编号
        if(queryUserFieldIsExist(NuoUserEntity::getUserCode,nuoUserDTO.getUserCode(),nuoUserDTO.getId())){
            log.error("用户编号已存在->{}",nuoUserDTO.getUserCode());
            throw new NuoException("用户编号已存在");
        }
        NuoUtil.isNotNull("部门名称不能为空",nuoUserDTO.getDeptName());
        NuoUtil.isNotNull("部门id不能为空",nuoUserDTO.getDeptId());
        NuoUtil.isNotNull("真实名称不能为空",nuoUserDTO.getRealName());
        // 密码设置
        if(StrUtil.isEmpty(nuoUserDTO.getPassword()) && ObjectUtil.isNull(nuoUserDTO.getId())){
            //新增
             nuoUserDTO.setPassword(NuoPasswordEncoder.DEFAUTL_PASSWORD);
             nuoUserDTO.setPassword(nuoPasswordEncoder.encode(nuoUserDTO.getPassword()));
        }else if(StrUtil.isNotEmpty(nuoUserDTO.getPassword())){
            if( StrUtil.containsBlank(nuoUserDTO.getPassword())){
                throw new NuoException("密码不能存在空白字符");
            }
            //密码不为空
            nuoUserDTO.setPassword(nuoPasswordEncoder.encode(nuoUserDTO.getPassword()));
        }

        // 设置公司
        NuoDeptEntity deptEntity = nuoDeptService.queryDeptById(nuoUserDTO.getDeptId());
        if(ObjectUtil.isNull(deptEntity)){
            log.error("部门不存在->{}",nuoUserDTO.getUserName());
            throw new NuoException("部门不存在");
        }
        if(deptEntity.getIsCompany() == NuoUtil.YES){
            nuoUserDTO.setCompanyId(deptEntity.getId());
            nuoUserDTO.setCompanyName(deptEntity.getDeptName());
        }else{
            nuoUserDTO.setCompanyId(deptEntity.getCompanyId());
            nuoUserDTO.setCompanyName(deptEntity.getCompanyName());
        }
        nuoUserDTO.setAccountNonExpired(NuoUtil.YES);
        nuoUserDTO.setCredentiaIsNonexpired(NuoUtil.YES);
        nuoUserDTO.setEnabled(NuoUtil.YES);
        NuoUserEntity entity = Convert.convert(NuoUserEntity.class,nuoUserDTO);
        this.saveOrUpdate(entity);
    }

    @Override
    public NuoUserEntity queryUserInfoByUserName(String userName) {
        if(StrUtil.isEmpty(userName)){
            log.error("参数不能为空->{}",userName);
            throw  new NuoException(NuoErrorStatus.PARAM_IS_NOT_NULL);
        }
        LambdaQueryWrapper<NuoUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NuoUserEntity::getUserName,userName);
        return nuoUserDao.selectOne(wrapper);
    }


    @Override
    public Boolean queryUserFieldIsExist(SFunction<NuoUserEntity, ?> field,String fieldValue, Object id) {
        if(StrUtil.isEmpty(fieldValue)){
            log.error("参数不能为空->{}",fieldValue);
            throw  new NuoException(NuoErrorStatus.PARAM_IS_NOT_NULL);
        }
        LambdaQueryWrapper<NuoUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(field,fieldValue);
        NuoUserEntity nuoUserEntity = nuoUserDao.selectOne(wrapper);
        if(ObjectUtil.isNotNull(nuoUserEntity)){
            if(String.valueOf(nuoUserEntity.getId()).equals(String.valueOf(id))){
                //查出的数据与id相等，则为修改
                return false;
            }
            //若不相等则查出的数据并不是修改内容，则为存在
        }else{
            //通过用户名未查出来数据，则不存在
            return  false;
        }
        return true;
    }

    @Override
    public void deleteUserById(Long id) {
        nuoUserDao.deleteById(id);
    }

    @Override
    public NuoUserDTO queryUserById(String id) {
        NuoUserEntity entity = nuoUserDao.selectById(id);
        return entity != null?Convert.convert(NuoUserDTO.class,entity): null;
    }

    @Override
    public IPage<NuoUserEntity> queryUserPageByParam(Page page,NuoUserDTO nuoUserDTO) {
        LambdaQueryWrapper<NuoUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(nuoUserDTO.getRealName()),NuoUserEntity::getRealName,nuoUserDTO.getRealName());
        wrapper.like(StrUtil.isNotBlank(nuoUserDTO.getUserName()),NuoUserEntity::getUserName,nuoUserDTO.getUserName());
        wrapper.like(StrUtil.isNotBlank(nuoUserDTO.getDeptName()),NuoUserEntity::getDeptName,nuoUserDTO.getDeptName());
        wrapper.orderByDesc(NuoUserEntity::getCreateDate);
        return nuoUserDao.selectPage(page, wrapper);
    }

}